package com.github.ghsea.scheduler.controller;

import com.github.ghsea.scheduler.core.TaskScheduler;
import com.github.ghsea.scheduler.dto.Result;
import com.github.ghsea.scheduler.dto.Task;
import com.github.ghsea.scheduler.entity.TaskEntity;
import com.github.ghsea.scheduler.service.TaskService;
import com.github.ghsea.scheduler.util.Converters;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author guhai
 * @since 2021/6/17 20:29
 */

@RestController
@RequestMapping("/task")
public class TaskAcceptor {

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private TaskService taskService;

    @PostMapping(path = "/start")
    public Result<Void> startTask(@Validated @RequestBody Task task) {
        System.out.println(task);
        TaskEntity taskEntity=Converters.FROM_TASK.apply(task);
        taskService.insertTask(taskEntity);
        taskScheduler.schedule(task);
        return Result.success();
    }

    @PostMapping(path = "/stop")
    public Result<Void> stopTask(@Validated @RequestBody String taskId) {
        Date stopTime = new Date();
        taskService.stopTask(taskId, stopTime);
        taskScheduler.stop(taskId, stopTime);
        return Result.success();
    }

}
